//
//  EDDividendListViewController.m
//  EDF
//
//  Created by 微笑吧阳光 on 2019/7/10.
//  Copyright © 2019 p. All rights reserved.
//

#import "EDDividendListViewController.h"
#import "EDDividendListTableViewCell.h"
#import "UIAlignmentLabel.h"
#import "CJItemWelfareModel.h"

@interface EDDividendListViewController ()
{
    NSInteger _pageNum;
}
@property (nonatomic,strong) NoNetworkView * workView;
@end
@implementation EDDividendListViewController
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
      self.ks_TableView.frame = CGRectMake(0, 10, kScreenWidth, kScreenHeight-kStatusBarAndNavigationBarHeight-60-150);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNum = 0;
    [self creatUI];
    [self ks_tableAddFootRequst];
    [self ks_tableAddHeaderRequstRefush];
    if (@available(iOS 11.0, *)) {
        self.ks_TableView.estimatedRowHeight =0;
        self.ks_TableView.estimatedSectionHeaderHeight =0;
        self.ks_TableView.estimatedSectionFooterHeight =0;
        self.ks_TableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
}
-(void)creatUI{
    
    self.modelsArry = [NSMutableArray array];
    self.view.backgroundColor =kRGBColor(245, 245, 245);
    self.ks_TableView.frame = CGRectMake(0, 10, kScreenWidth, kScreenHeight-kStatusBarAndNavigationBarHeight-60-150);
    self.ks_TableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.ks_TableView];
    
    UIView * bottomView = [BBControl createViewWithFrame:CGRectMake(0, self.ks_TableView.bottom, kScreenWidth, 150)];
    bottomView.backgroundColor =kRGBColor(245, 245, 245);
    [self.view addSubview:bottomView];
    
    
    UIAlignmentLabel * fristLab2 =[UIAlignmentLabel new];
    fristLab2.frame =CGRectMake(0, 20, kScreenWidth, 20);
    fristLab2.text =@"更多详情请前往电脑端查看";
    fristLab2.font = AppFont(14);
    fristLab2.textColor = kRGBColor(90, 90, 90);
    fristLab2.textAlignment = UITextAlignmentCenter;
    [bottomView addSubview:fristLab2];
    
    UIButton * bottomBtn = [BBControl createButtonWithFrame:CGRectMake(60, fristLab2.bottom+20, kScreenWidth-120, 50) target:self SEL:@selector(allGetBtnClick:) title:@"一键领取"];
    [bottomBtn setBackgroundImage: [UIImage imageNamed:@"login_Btn_bg"] forState:0];
    [bottomBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [bottomBtn setTitleColor:[UIColor whiteColor] forState:0];
    [bottomView addSubview:bottomBtn];

}

-(void)getData_LoadingMore{
    _pageNum ++;
    [self refushData:NO];
}
-(void)getData_Refush{
      _pageNum = 0;
    [self refushData:YES];
    //  [self.ks_TableView.mj_header endRefreshing];
    
}
-(void)refushData:(BOOL)isRefush{
    
    if (self.showType==0) {
        NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"User_welfareMobileActionWelfareCore"];
        NSMutableDictionary *  diccc = [NSMutableDictionary dictionary];
        [diccc setValue:@(_pageNum) forKey:@"curpage"];
        
        WEAKSELF
        [[SmileHttpTool sharedInstance] GET :url parameters:nil origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
            STRONGSELFFor(weakSelf);
            
            if (isRefush ==YES) {
                [strongSelf.modelsArry removeAllObjects];
            }
            NSError *errorData;
            NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
            NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
            NSDictionary  *dict = [dict001 jsonDict:@"data"];
            NSArray *  dataArr = [dict jsonArray:@"date"];
            NSInteger allPage = [dict jsonInteger:@"pages"];
            NSInteger curpage = [dict jsonInteger:@"pageNumber"];
            if (isRefush==NO) {
                if (allPage == curpage+1) {
                    //没数据了
                    [strongSelf.ks_TableView.mj_footer endRefreshingWithNoMoreData];
                    return;
                }
            }
            
            for (NSDictionary * modelDicc in dataArr) {
                CJItemWelfareModel * modell = [[CJItemWelfareModel alloc]initWithDictionary:modelDicc error:nil];
                [strongSelf.modelsArry addObject:modell];
            }
            
            //        if (isRefush==YES && dataArr.count==0) {
            //            strongSelf.nodtaLab.hidden = NO;
            //        }else{
            //            strongSelf.nodtaLab.hidden = YES;
            //        }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                      [self placeholderViewWithFrame:self.ks_TableView.frame NoNetwork:NO];
            });
            [self.ks_TableView.mj_footer endRefreshing];
            [self.ks_TableView.mj_header endRefreshing];
            [strongSelf.ks_TableView reloadData];
            NSLog(@"User_welfareMobileActionWelfareCore---%@",dict);
            
        } failure:^(id responseObject, NSError *error) {
            NSLog(@"error----%@",error);
            STRONGSELFFor(weakSelf);
            [strongSelf.ks_TableView.mj_footer endRefreshing];
            [strongSelf.ks_TableView.mj_header endRefreshing];
            //  [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
        }];
        
    }else{
        //User_GetgetgetCurrencyAll
        NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"User_GetgetgetCurrencyAll"];
        NSMutableDictionary *  diccc = [NSMutableDictionary dictionary];
        [diccc setValue:@(_pageNum) forKey:@"curpage"];
        
        WEAKSELF
        [[SmileHttpTool sharedInstance] GET :url parameters:nil origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
            STRONGSELFFor(weakSelf);
            if (isRefush ==YES) {
                [strongSelf.modelsArry removeAllObjects];
            }
            NSError *errorData;
            NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
            NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
            NSDictionary  *dict = [dict001 jsonDict:@"data"];
            NSArray *  dataArr = [dict jsonArray:@"date"];
            NSInteger allPage = [dict jsonInteger:@"pages"];
            NSInteger curpage = [dict jsonInteger:@"pageNumber"];
            if (isRefush==NO) {
                if (allPage == curpage+1) {
                    //没数据了
                    [strongSelf.ks_TableView.mj_footer endRefreshingWithNoMoreData];
                    return;
                }
            }
            
            for (NSDictionary * modelDicc in dataArr) {
                CJItemWelfareModel * modell = [[CJItemWelfareModel alloc]initWithDictionary:modelDicc error:nil];
                [strongSelf.modelsArry addObject:modell];
            }
            
            //        if (isRefush==YES && dataArr.count==0) {
            //            strongSelf.nodtaLab.hidden = NO;
            //        }else{
            //            strongSelf.nodtaLab.hidden = YES;
            //        }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self placeholderViewWithFrame:self.ks_TableView.frame NoNetwork:NO];
            });
            [self.ks_TableView.mj_footer endRefreshing];
            [self.ks_TableView.mj_header endRefreshing];
            [strongSelf.ks_TableView reloadData];
            NSLog(@"User_welfareMobileActionWelfareCore---%@",dict);
            
        } failure:^(id responseObject, NSError *error) {
            NSLog(@"error----%@",error);
            STRONGSELFFor(weakSelf);
            [strongSelf.ks_TableView.mj_footer endRefreshing];
            [strongSelf.ks_TableView.mj_header endRefreshing];
            //  [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
        }];
        
        
        
    }
    
  
    
}



-(void)allGetBtnClick:(UIButton*)sender{
    
    if (self.modelsArry.count==0) {
        ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"error" andTitleStr:@"暂无数据可领取" andlightStr:@""];
        [toast showLXAlertView];
        return;
        
    }
       
    if ([self isHaveData ] ==YES) {
        WEAKSELF
        [[SmileAlert sharedInstance] mazi_alertContent:@"您有优惠卡可使用，确定一键领取吗？" AndBlock:^(BOOL sure) {
            STRONGSELFFor(weakSelf);
            if (sure==YES) {
                 [strongSelf actionAll_DataRequest];
            }
        }];
        
    }else{
        
        
        [self actionAll_DataRequest];
        
    }
    
}

-(BOOL)isHaveData{
    
   static  BOOL isHave = NO;
       [self.modelsArry enumerateObjectsUsingBlock:^(CJItemWelfareModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj) {
                if (!kStringIsEmpty(obj.coupon_id)) {
                    NSLog(@"coupon_id:%@ @",obj.coupon_id);
                    isHave = YES;
                    *stop = YES;//手动停止遍历
                }
            }else{
                NSLog(@"结束了，但没找到");
            }
        }];
    
    return isHave;
}
-(void)actionAll_DataRequest{
    
    
    
    if (self.showType==0) {
        NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"User_welfareGetAllWelfare"];
        WEAKSELF
        [[SmileHttpTool sharedInstance] GET :url parameters:nil origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
            STRONGSELFFor(weakSelf);
            NSError *errorData;
            NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
            NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
            NSString *responseObjectStr =[dict001 jsonString:@"statusCode"];
            NSLog(@"responseObjectStr----%@",responseObjectStr);
            if ([responseObjectStr isEqualToString:@"SUCCESS"]) {
                //[JMNotifyView showNotify:@"领取成功" isSuccessful:NO];
                dispatch_async(dispatch_get_main_queue(), ^{
                    ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"success" andTitleStr:[dict001 jsonString:@"data"] andlightStr:@""];
                    [toast showLXAlertView];
                    [strongSelf.ks_TableView.mj_header beginRefreshing];
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"error" andTitleStr:@"领取失败" andlightStr:@""];
                    [toast showLXAlertView];
                });
            }
            [strongSelf.ks_TableView reloadData];
        } failure:^(id responseObject, NSError *error) {
            NSLog(@"error----%@",error);
            [WJUnit showMessage:@"请求错误"];
        }];
        
    }else{
        NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"User_welfareGetALLSingCurrency"];
        WEAKSELF
        [[SmileHttpTool sharedInstance] GET :url parameters:nil origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
            STRONGSELFFor(weakSelf);
            NSError *errorData;
            NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
            NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
            NSString *responseObjectStr =[dict001 jsonString:@"statusCode"];
            NSLog(@"responseObjectStr----%@",responseObjectStr);
            if ([responseObjectStr isEqualToString:@"SUCCESS"]) {
                //[JMNotifyView showNotify:@"领取成功" isSuccessful:NO];
                dispatch_async(dispatch_get_main_queue(), ^{
                    ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"success" andTitleStr:[dict001 jsonString:@"data"] andlightStr:@""];
                    [toast showLXAlertView];
                    [strongSelf.ks_TableView.mj_header beginRefreshing];
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"error" andTitleStr:@"领取失败" andlightStr:@""];
                    [toast showLXAlertView];
                });
            }
            [strongSelf.ks_TableView reloadData];
        } failure:^(id responseObject, NSError *error) {
            NSLog(@"error----%@",error);
          [WJUnit showMessage:@"请求错误"];
        }];
        
        
    }
    
    
    
}
-(void)cell_ActionSingelWith:(NSIndexPath *)index{
    CJItemWelfareModel * modell = self.modelsArry[index.row];
    
    
    if (kStringIsEmpty(modell.coupon_id)) {
         [self action_WithAlertPopSeclectResult:YES andModel:modell];
    }else{
        WEAKSELF
        [[SmileAlert sharedInstance] couponGetMessage_alertContent:@"" AndBlock:^(BOOL sure) {
            STRONGSELFFor(weakSelf);
            if (sure==YES) {
                [strongSelf action_WithAlertPopSeclectResult:YES andModel:modell];
            }else{
                [strongSelf action_WithAlertPopSeclectResult:NO andModel:modell];
                
            }
        }];
       
    }

}


-(void)action_WithAlertPopSeclectResult:(BOOL )isSure andModel:(CJItemWelfareModel * )modell
{
      if (self.showType==1) {
          NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"User_welfareGetSingCurrency"];
          WEAKSELF
          NSMutableDictionary *  diccc = [NSMutableDictionary dictionary];
          [diccc setValue:modell.id forKey:@"id"];
          if (isSure ==YES) {
               [diccc setValue:modell.coupon_id forKey:@"coupon_id"];
          }
          [[SmileHttpTool sharedInstance] GET :url parameters:diccc origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
              STRONGSELFFor(weakSelf);
              NSError *errorData;
              NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
              NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
              NSString *responseObjectStr =[dict001 jsonString:@"statusCode"];
              NSLog(@"responseObjectStr----%@",responseObjectStr);
              if ([responseObjectStr isEqualToString:@"SUCCESS"]) {
                 //[JMNotifyView showNotify:@"领取成功" isSuccessful:NO];
    
                  dispatch_async(dispatch_get_main_queue(), ^{
                      if (isSure==YES) {
                          ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"success" andTitleStr:[NSString stringWithFormat:@"已翻倍，成功领取%@发币",[NSString stringWithFormat:@"%ld",[modell.extra_amount integerValue]]] andlightStr:[NSString stringWithFormat:@"%ld",[modell.extra_amount integerValue]]];
                                                                   [toast showLXAlertView];
                          
                      }else{
                          ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"success" andTitleStr:[NSString stringWithFormat:@"成功领取%@发币",[NSString stringWithFormat:@"%ld",[modell.amount integerValue]]] andlightStr:[NSString stringWithFormat:@"%ld",[modell.amount integerValue]]];
                                              [toast showLXAlertView];
                          
                      }
                      //LoginSusessNotificationse
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"User_welfareGetSingCurrency" object:nil];
                    
                      [strongSelf.ks_TableView.mj_header beginRefreshing];
                  });
              }else{
                  dispatch_async(dispatch_get_main_queue(), ^{
                      ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"error" andTitleStr:@"领取失败" andlightStr:@""];
                      [toast showLXAlertView];
                  });
              }
              [strongSelf.ks_TableView reloadData];
          } failure:^(id responseObject, NSError *error) {
              NSLog(@"error----%@",error);
               [WJUnit showMessage:@"请求错误"];
          }];
          
      }else{
          NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"User_welfareGetSingleWelfare"];
          WEAKSELF
          NSMutableDictionary *  diccc = [NSMutableDictionary dictionary];
          [diccc setValue:modell.id forKey:@"id"];
          if (isSure ==YES) {
                [diccc setValue:modell.coupon_id forKey:@"coupon_id"];
            }
          [[SmileHttpTool sharedInstance] GET :url parameters:diccc origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
              STRONGSELFFor(weakSelf);
              NSError *errorData;
              NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
              NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
              NSString *responseObjectStr =[dict001 jsonString:@"statusCode"];
              NSLog(@"responseObjectStr----%@",responseObjectStr);
              if ([responseObjectStr isEqualToString:@"SUCCESS"]) {
                  dispatch_async(dispatch_get_main_queue(), ^{
                      ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"success" andTitleStr:[NSString stringWithFormat:@"福利已领取"] andlightStr:@""];
                      [toast showLXAlertView];
                      [strongSelf.ks_TableView.mj_header beginRefreshing];
                      
                          [[NSNotificationCenter defaultCenter] postNotificationName:@"User_welfareGetSingCurrency" object:nil];
                      
                  });
                  
              }else{
                  dispatch_async(dispatch_get_main_queue(), ^{
                      ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"error" andTitleStr:@"领取发币失败" andlightStr:@""];
                      [toast showLXAlertView];
                  });
              }
              [strongSelf.ks_TableView reloadData];
          } failure:^(id responseObject, NSError *error) {
              NSLog(@"error----%@",error);
               [WJUnit showMessage:@"请求错误"];
          }];
          
    
     }
    
    
}
//User_welfareGetSingCurrency 领取单个发币
//User_welfareGetALLSingCurrency 领取所有发币
//User_welfareGetAllWelfare 所有福利领取
//User_welfareGetSingleWelfare 单个福利领取

- (void)placeholderViewWithFrame:(CGRect)frame NoNetwork:(BOOL)NoNetwork
{
    if (self.modelsArry.count == 0)
    {
        [_workView removeFromSuperview];
        _workView = [[NoNetworkView alloc] initWithFrame:frame NoNetwork:NoNetwork];
        [self.ks_TableView addSubview:_workView];
    }else
    {
        [_workView dissmiss];
    }
}

#pragma mark ----,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  self.modelsArry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"EDDividendListTableViewCell";
    EDDividendListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = (EDDividendListTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:@"EDDividendListTableViewCell" owner:self options:nil] lastObject];
    }
    cell.showType = self.showType;
    CJItemWelfareModel * modell = self.modelsArry[indexPath.row];
    if (self.showType==0) {
    cell.itemModel = modell;
       //红利
    }else{
        //发币
    
        cell.icon.image = [UIImage imageNamed:@"icon_jinbi"];
        cell.nameLab.text = modell.detail;
               cell.numLab.text = [NSString stringWithFormat:@"%.0f",[modell.amount floatValue]];
               NSString * time = [modell.create_date stringByReplacingOccurrencesOfString:@"%20" withString:@" "];
               cell.timeLab.text =  [NSString stringWithFormat:@"派发日期:%@",time];
    }
    if (kStringIsEmpty(modell.coupon_id)) {
       cell.tishiImage.hidden = YES;
    }else{
        cell.tishiImage.hidden = NO;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    WEAKSELF
    [cell.actionBtn add_BtnClickHandler:^(NSInteger tag) {
        STRONGSELFFor(weakSelf);
        [strongSelf cell_ActionSingelWith:indexPath];;
    }];
    return cell;
    
}
#pragma makr ------UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 65;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
}

@end
